import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { Button, ProgressBar, TextInput, Chip } from 'react-native-paper';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

// 预设的兴趣标签
const PRESET_INTERESTS = [
  '电影', '音乐', '阅读', '旅行', '美食', '健身', 
  '摄影', '绘画', '舞蹈', '游戏', '编程', '烹饪', 
  '瑜伽', '冥想', '徒步', '露营', '钓鱼', '骑行',
  '游泳', '跑步', '篮球', '足球', '网球', '高尔夫',
  '宠物', '园艺', '手工', '收藏', '志愿者', '咖啡',
  '茶艺', '红酒', '历史', '科技', '时尚', '设计'
];

// 预设的爱好标签
const PRESET_HOBBIES = [
  '看电影', '听音乐会', '读小说', '国内旅行', '国际旅行', '尝试新餐厅', 
  '健身房锻炼', '户外运动', '街拍', '素描', '现代舞', '桌游', 
  '移动游戏', '主机游戏', 'PC游戏', '前端开发', '后端开发', '中餐烹饪', 
  '西餐烹饪', '热瑜伽', '冥想减压', '城市徒步', '野外徒步', '野营', 
  '海钓', '江河钓鱼', '公路骑行', '山地骑行', '自由泳', '蛙泳', 
  '马拉松', '街头篮球', '五人制足球', '网球单打', '高尔夫练习场', '猫咪饲养', 
  '狗狗训练', '室内植物', '花园种植', '编织', '陶艺', '邮票收藏', 
  '硬币收藏', '社区志愿者', '手冲咖啡', '品茶', '品酒', '古代历史', 
  '现代历史', '人工智能', '区块链', '服装搭配', '室内设计', '平面设计'
];

export default function InterestsScreen() {
  const colorScheme = useColorScheme();
  const { userInfo, userToken, updateProfile } = useAuth();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  // 表单状态
  const [interests, setInterests] = useState<string[]>(userInfo?.interests || []);
  const [hobbies, setHobbies] = useState<string[]>(userInfo?.hobbies || []);
  const [customInterest, setCustomInterest] = useState('');
  const [customHobby, setCustomHobby] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  // 如果用户未登录，重定向到登录页面
  useEffect(() => {
    if (!userToken) {
      router.replace('/auth/login');
    }
  }, [userToken]);

  // 添加兴趣
  const toggleInterest = (interest: string) => {
    if (interests.includes(interest)) {
      setInterests(interests.filter(i => i !== interest));
    } else {
      setInterests([...interests, interest]);
    }
  };

  // 添加自定义兴趣
  const addCustomInterest = () => {
    if (customInterest.trim() && !interests.includes(customInterest.trim())) {
      setInterests([...interests, customInterest.trim()]);
      setCustomInterest('');
    }
  };

  // 添加爱好
  const toggleHobby = (hobby: string) => {
    if (hobbies.includes(hobby)) {
      setHobbies(hobbies.filter(h => h !== hobby));
    } else {
      setHobbies([...hobbies, hobby]);
    }
  };

  // 添加自定义爱好
  const addCustomHobby = () => {
    if (customHobby.trim() && !hobbies.includes(customHobby.trim())) {
      setHobbies([...hobbies, customHobby.trim()]);
      setCustomHobby('');
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    if (interests.length === 0) {
      Alert.alert('提示', '请至少选择一个兴趣爱好');
      return;
    }

    setIsLoading(true);
    try {
      // 更新用户兴趣爱好信息
      const success = await updateProfile({
        interests,
        hobbies
      });

      if (success) {
        // 进入下一步
        router.push('/profile-setup/values');
      } else {
        Alert.alert('错误', '更新个人资料失败，请重试');
      }
    } catch (error) {
      console.error('Update profile error:', error);
      Alert.alert('错误', '发生未知错误，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>兴趣爱好</ThemedText>
            <ThemedText style={styles.subtitle}>
              选择您感兴趣的活动和爱好，这将帮助我们为您匹配志同道合的人
            </ThemedText>
          </View>

          <ProgressBar 
            progress={4/6} 
            color={tintColor} 
            style={styles.progressBar} 
          />

          <View style={styles.formContainer}>
            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>兴趣类别 (已选择 {interests.length})</ThemedText>
              <ThemedText style={styles.subLabel}>选择您感兴趣的大类别</ThemedText>
              
              <View style={styles.chipContainer}>
                {PRESET_INTERESTS.map((interest, index) => (
                  <Chip
                    key={index}
                    selected={interests.includes(interest)}
                    onPress={() => toggleInterest(interest)}
                    style={[
                      styles.chip,
                      interests.includes(interest) && { backgroundColor: tintColor + '20' }
                    ]}
                    textStyle={[
                      styles.chipText,
                      interests.includes(interest) && { color: tintColor }
                    ]}
                  >
                    {interest}
                  </Chip>
                ))}
              </View>

              <View style={styles.inputWithButton}>
                <TextInput
                  value={customInterest}
                  onChangeText={setCustomInterest}
                  mode="outlined"
                  placeholder="添加自定义兴趣"
                  style={styles.customInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  onSubmitEditing={addCustomInterest}
                />
                <Button
                  mode="contained"
                  onPress={addCustomInterest}
                  style={styles.addButton}
                  theme={{ roundness: 10 }}
                >
                  添加
                </Button>
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>具体爱好 (已选择 {hobbies.length})</ThemedText>
              <ThemedText style={styles.subLabel}>选择您喜欢的具体活动</ThemedText>
              
              <View style={styles.chipContainer}>
                {PRESET_HOBBIES.map((hobby, index) => (
                  <Chip
                    key={index}
                    selected={hobbies.includes(hobby)}
                    onPress={() => toggleHobby(hobby)}
                    style={[
                      styles.chip,
                      hobbies.includes(hobby) && { backgroundColor: tintColor + '20' }
                    ]}
                    textStyle={[
                      styles.chipText,
                      hobbies.includes(hobby) && { color: tintColor }
                    ]}
                  >
                    {hobby}
                  </Chip>
                ))}
              </View>

              <View style={styles.inputWithButton}>
                <TextInput
                  value={customHobby}
                  onChangeText={setCustomHobby}
                  mode="outlined"
                  placeholder="添加自定义爱好"
                  style={styles.customInput}
                  outlineColor="#CCCCCC"
                  activeOutlineColor={tintColor}
                  theme={{ roundness: 10 }}
                  onSubmitEditing={addCustomHobby}
                />
                <Button
                  mode="contained"
                  onPress={addCustomHobby}
                  style={styles.addButton}
                  theme={{ roundness: 10 }}
                >
                  添加
                </Button>
              </View>
            </View>
          </View>

          <View style={styles.buttonContainer}>
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.button}
              labelStyle={styles.buttonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
            >
              下一步
            </Button>

            <Button
              mode="outlined"
              onPress={() => router.back()}
              style={[styles.button, styles.backButton]}
              labelStyle={styles.backButtonText}
              theme={{ roundness: 10 }}
            >
              返回
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    marginTop: 40,
    marginBottom: 30,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    opacity: 0.7,
    marginBottom: 10,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    marginBottom: 30,
  },
  formContainer: {
    marginBottom: 30,
  },
  formGroup: {
    marginBottom: 25,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    fontWeight: '500',
  },
  subLabel: {
    fontSize: 14,
    marginBottom: 12,
    opacity: 0.7,
  },
  chipContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginBottom: 15,
  },
  chip: {
    margin: 4,
  },
  chipText: {
    fontSize: 14,
  },
  inputWithButton: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  customInput: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  addButton: {
    marginLeft: 10,
  },
  buttonContainer: {
    marginTop: 'auto',
    marginBottom: 20,
  },
  button: {
    marginBottom: 15,
    paddingVertical: 8,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  backButton: {
    borderColor: '#ccc',
  },
  backButtonText: {
    fontSize: 16,
  },
});
